﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing.Design;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using VersionComparer.Base;
using VersionComparer.DataModel.Actions;
using VersionComparer.Views;

namespace VersionComparer.DataModel
{
    public class BatchAction : Action
    {
        #region constructors
        public BatchAction(bool initialize ):base()
        {
            if (initialize)
            {
                OpenFileDialog fd = new OpenFileDialog();
                fd.Filter = "Bat files (*.bat)|*.bat|Cmd files (*.cmd)|*.cmd|Exe files (*.exe)|*.exe";
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    Name = System.IO.Path.GetFileNameWithoutExtension(fd.FileName);
                    Path = fd.FileName;
                }
                else
                    throw new Exception("No file chosen");
            }
        }
        public BatchAction()
            : this(false)
        {
            base.RefreshAfterFinish = true;
            Name = "<<new action>>";
        }
        #endregion constructors

        [DisplayName ("Path")]
        [Description ("Path for the batch or executable file to be executed")]
        [Editor(typeof(BatchFileSelectorTypeEditor), typeof(UITypeEditor))]
        public string Path
        {
            get;
            set;
        }

        protected override void ExecuteAction(MainForm mainForm, ComparableItem[] focusedselectedItems, ComparableItem[] unfocusedselectedItems)
        {
            ThreadManager threadManager = new ThreadManager();
            threadManager.StartNew((x) => ExecuteSync(x, mainForm, focusedselectedItems, unfocusedselectedItems));
        }
        void ExecuteSync(ManagedThread threadManager, MainForm mainForm, ComparableItem[] focusedselectedItems, ComparableItem[] unfocusedselectedItems)
        {
            Process process = new Process();
            
            List<string> parameters = new List<string>();

            StringBuilder builder = new StringBuilder();
            foreach (ComparableItem item in focusedselectedItems)
            {
                string path = item.Text;

                if (!parameters.Contains(path))
                {
                    parameters.Add(path);
                    builder.AppendFormat("\"{0}\" ", path);
                }
            }
            
            process.StartInfo = new ProcessStartInfo(Path, builder.ToString());
            process.Start();

            if (RefreshAfterFinish)
            {
                process.WaitForExit();
                mainForm.Execute(mainForm.RefreshDifferences);
            }
        }

    }
}
